# clean_value.py
# usage: 
# python ./src/tools/clean_value.py --query "C区工单数量最高的一天"

import json
import sys
from typing import List, Dict, Tuple

def load_parameters(file_path: str) -> List[Dict]:
    """
    从文件中加载参数配置
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            parameters = json.load(f)
        return parameters
    except Exception as e:
        print(f"Error loading parameters file: {e}")
        sys.exit(1)

def find_matching_value(text: str, parameters: List[Dict]) -> List[Tuple[str, str]]:
    """
    在文本中查找匹配的values，返回 (value, parameter) 对
    """
    matches = []
    
    for param_item in parameters:
        parameter = param_item.get("parameter", "")
        values = param_item.get("values", [])
        
        for value in values:
            if value in text:
                matches.append((value, parameter))
    
    # 按value长度降序排序，避免子串先匹配（例如 "A区" 和 "A区B"）
    matches.sort(key=lambda x: len(x[0]), reverse=True)
    
    return matches

def clean_text(text: str) -> str:
    """
    清理文本，将匹配的values替换为 {parameter}
    """
    
    parameters_file = "./data/parameters.txt"
    
    # 加载参数
    parameters = load_parameters(parameters_file)

    matches = find_matching_value(text, parameters)
    
    # 逐个替换，由于已排序，长的value会先被替换
    for value, parameter in matches:
        text = text.replace(value, f"{{{parameter}}}")
    
    return text

def main():
    if len(sys.argv) != 3 or sys.argv[1] != "--query":
        print("Usage: python clean_value.py --query 'your question'")
        sys.exit(1)
    
    query = sys.argv[2]
    
    # 处理查询
    result = clean_text(query)
    
    print(result)

if __name__ == "__main__":
    main()